﻿/// <reference path="/js/jquery.js" />
var d = new Date();
var y = d.getFullYear();
var m = d.getMonth();
var oTable;

$(document).ready(function() {
    //$(".form-buttom").click(sayHelloAjax);
    $("#cmdCarregar,#search").click(loadTableAjax);
    $("#cmdCarregar,#procedureEstatistica").click(loadProcedureTableAjax);
    $("#cboMes").val(m + 1);
    $("#cboAno").val(y);
    $("#resultContainer").hide();
    $("#dados").hide();
});

function loadProcedureTableAjax() {
    var ano  = $("#cboAno").val();
    var mes  = $("#cboMes").val();
    var loja = $("#hidLojaId").val();
    var branchno = $("#hidBranchno").val();
    var data = "{ 'ano': " + ano + ", 'mes': " + mes + ", 'loja': " + loja + ", 'branchno': " + branchno + "}";   
    
    $('#loading').show();
    $("#cmdCarregar,#search").hide();
    $("#cmdCarregar,#procedureEstatistica").hide();
    
    $.ajax({
        type        : "POST",
        url         : "planejamentoservice.asmx/BuildDataProcedure",
        contentType : "application/json; charset=utf-8",
        dataType    : "json",
        data        : data,
        async       : false,
        success     : loadRerturnProcedure,
        error       : ajaxFailed
    }); 
    
}

function loadRerturnProcedure(result) {
    alert('Processo de carga da estatistica atualizado. Aguarde carregamento da tabela.');
    loadTableAjax();
    $("#cmdCarregar,#search").show();
    $("#cmdCarregar,#procedureEstatistica").show();
}
    
function loadTableAjax() {
    var ano  = $("#cboAno").val();
    var mes  = $("#cboMes").val();
    var loja = $("#hidLojaId").val();
    var data = "{ 'ano': " + ano + ", 'mes': " + mes + ", 'loja': " + loja + "}";   
    
    $('#loading').show();
    
    $.ajax({
        type        : "POST",
        url         : "planejamentoservice.asmx/BuildDataTable",
        contentType : "application/json; charset=utf-8",
        dataType    : "json",
        data        : data,
        success     : loadTableAjaxSucceeded,
        error       : ajaxFailed
    }); 
}
    
function loadTableAjaxSucceeded(result) {
    $('#result').html( '<table cellpadding="2" cellspacing="1" border="0" class="display" style=""  id="example"></table>' );
    $("#resultContainer").show();
   
    var conf = {
        "aaData": result.d.aaData,
        "aoColumns": result.d.aoColumns,
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": false,
        "bSort": false,
        "bInfo": false,
        "bAutoWidth": false
    };
    
    oTable = $('#example').dataTable(conf);
    applyTableConfig();
    addEditableRegions();
    $('#loading').hide();
}
    
function applyTableConfig() {
    $("#example.display thead tr").addClass("th");
    $("#example.display thead th").css("width", "50px");
    $("#example.display tbody tr").css("height", "22px");
    $("#example.display thead tr th").filter(":first-child").css("text-align", "left");
    $("#example.display tbody tr td").addClass("alc");
    $("#example.display tbody tr td").filter(":first-child").removeClass("alc");
    $("#example.display tbody tr.odd").addClass("cor-1");
    $("#example.display tbody tr.even").addClass("cor-2");
    $("#example.display tbody tr.even td").wrapInner("<span class='editable' style='cursor:crosshair;display:block;width:100%'/>");
    $("#example.display tbody tr.even td:nth-col(1)").children("span").removeClass("editable");
}
  
function addEditableRegions() {
    var reverted = null;
    
    $.editable.addInputType('masked', {
        element: function(settings, original) {
            reverted = original.revert;
            $("#dados").html(original.revert);

            $.mask.masks.custom = { mask: settings.mask, type: 'reverse' };
            var input = $('<input type="text" class="text-field" style="width:100%" alt="custom" />').setMask();

            $(this).append(input);
            
            return (input);
        },
        submit: function(settings, original) {
            $('#loading').show();
        },
        content: function(data, settings, original) {
            /*
            data = "dalton";
            alert(original);
            return(data);
            $("#x", this).children().each(function() {
                alert("x");
                $(this).val("dalton");
            }) ;*/
        }
    });

    $(".editable").editable(function(value, settings) {
        var codPlan = $("#dados").find("#codigo").val();
        var valPlan = value;
        
        if(valPlan == '') valPlan = 0;
        
        salvarPlanejamento(codPlan, valPlan);

        var newDados = $("#dados");
        newDados.html(reverted).find("#valor").text(valPlan);
        
        return ( newDados.html() );
        
        /*
        var colObj = $(this).parent().parent().children();
        var rowObj = colObj.parent("tr");
        var col = colObj.index($(this).parent());
        var row = colObj.parent("tr").index();
        var dia = rowObj.children(":first-child")
        col = col + 1;
        var hor = $("#example.display thead tr th:nth-col(" + col + ")");
        alert(value + " -->> " + dia.text() + " >> " + hor.text());
        */
    }, {
        tooltip: "Clique para editar",
        event: "click",
        style: "inherit",
        type: "masked",
        mask: "9.99"
    });
}

function salvarPlanejamento(codPlan, valPlan) {
    var data = "{ 'id': " + codPlan + ", 'val': " + valPlan + "}";   
    
    $.ajax({
        type        : "POST",
        url         : "planejamentoservice.asmx/UpdatePlanejamento",
        contentType : "application/json; charset=utf-8",
        dataType    : "json",
        data        : data ,
        success     : function(result) {
          $('#loading').hide();
          callback(result.d)
        },
        error       : ajaxFailed
    }); 
}

        
function AjaxSucceeded(result) {
    $("#result").text(result.d.Name);
}

function ajaxFailed(result) {
    //  TODO: Modificar isso para utilizar algum mecanismo mais elegante para reportar erros do servidor
    $('#loading').hide();
    alert("Erro durante a Requisição:\n" + result.status + ' ' + result.statusText + '\n\n' + result.responseText);
}
